from datetime import datetime
import logging

from controllers.errors.error import HTTPNotLoginError
from core.entities.account_role import AccountWrap
from extensions.ext_database import db
from pandas import DataFrame
from libs.exception import BaseHTTPException

from models.robot.rob_charater import RobCharacter
from models.robot.rob_domain import RobFunDomain
from models.robot.rob_emoji import RobEmojiPack
from models.robot.rob_timbre import RobTimbre
from models.robot.robots import AgentType, RobotCharacterMap, Robots,RobotExtraInfo
from flask_babel import _

from services.errors.character import CharacterNotExistError
from services.errors.emoji import EmojiPackageNotExistError
from services.errors.fun_domain import FunDomainNotExistError
from services.errors.robots import RobotActiveNotifyError, RobotAlreadyActivatedError, RobotAreadyActiveByOthersError, RobotConfigIncompleteError, RobotNotActiveError, RobotNotExistError, RobotNotReadyError, RobotParameterError, RobotRemoteConfigError
from services.errors.timbre import TimbreNotExistError, TimbreNotSupportLanguageError
from services.log_service import LogAction, LogService
from services.robot.character_service import CharacterService
from services.robot.emoji_service import EmojiService
from services.robot.ip_city_service import CityService
from services.robot.robot_remote_service import RobotRemoteService
from services.robot.timbre_service import TimbreService

class RobotsService:
    @staticmethod
    def get_my_robots(account_id:str)->list[RobotExtraInfo]:
        rob_extra_infos:list[RobotExtraInfo] = db.session.query(RobotExtraInfo).filter(RobotExtraInfo.account_id==account_id).all()
        if not rob_extra_infos:
            return []
        for rob_extra_info in rob_extra_infos:
            if rob_extra_info.robot:
                if rob_extra_info.robot.cur_charater_id:
                    rob_extra_info.current_character = db.session.get(RobCharacter,rob_extra_info.robot.cur_charater_id)
                if rob_extra_info.robot.cur_timbre_id:
                    rob_extra_info.current_timbre = db.session.get(RobTimbre,rob_extra_info.robot.cur_timbre_id)
                if rob_extra_info.robot.cur_emoji_pack_id:
                    rob_extra_info.current_emoji_pack = db.session.get(RobEmojiPack,rob_extra_info.robot.cur_emoji_pack_id) 
        return rob_extra_infos
    
    @classmethod
    def active_robot(cls,robot_id:str,account:AccountWrap,nick_name:str|None,area_code:str|None=None)->dict:
        is_ready,ip_addr,bluetooth_id,h_ver,f_ver = RobotRemoteService.is_ready_to_active(robot_id)
        # is_ready = True
        if not is_ready:
            raise RobotNotReadyError()
        robot = db.session.query(Robots).filter(Robots.id==robot_id,Robots.tenant_id==account.current_tenant_id).first()
        if not robot:
            raise RobotNotExistError(robot_id)
        if robot.activated_at:
            raise RobotAlreadyActivatedError()
        rob_extra_info = db.session.get(RobotExtraInfo,robot_id)
        if rob_extra_info and rob_extra_info.account_id!=account.id:
            raise RobotAreadyActiveByOthersError()
        if rob_extra_info and rob_extra_info.account_id==account.id:
            raise RobotAlreadyActivatedError()
        if not robot.fun_domain:
            raise RobotConfigIncompleteError(_("The robot function domain is not configured."))
        try:
            fun_domain:RobFunDomain = robot.fun_domain
            if not fun_domain.default_character_id:
                raise RobotConfigIncompleteError(_("The domain need a default character."))
            if not fun_domain.default_timbre_id:
                raise RobotConfigIncompleteError(_("The domain need a default timbre."))
            if not fun_domain.default_emoji_pack_id:
                raise RobotConfigIncompleteError(_("The domain need a default emoji pack."))
            robot.h_version = h_ver
            robot.f_version = f_ver
            robot.bluetooth_id = bluetooth_id
            robot.cur_charater_id = fun_domain.default_character_id
            robot.cur_timbre_id = fun_domain.default_timbre_id
            robot.cur_emoji_pack_id = fun_domain.default_emoji_pack_id
            robot.activated_at = datetime.now()
            for character in fun_domain.characters:
                db.session.add(RobotCharacterMap(
                    robot_id=robot.id, # type: ignore
                    character_id=character.id # type: ignore
                ))
            if not area_code:
                ret = CityService.get_city_by_ip(ip_addr)
                if ret and "cityCode" in ret:
                    area_code = ret["cityCode"]
            robot_name = f"{nick_name}的小精灵" if nick_name else "小精灵"
            rob_extra_info = RobotExtraInfo(
                id=robot.id,# type: ignore
                tenant_id = robot.tenant_id,# type: ignore
                account_id=account.id,# type: ignore
                user_name=nick_name if nick_name else account.name,# type: ignore
                robot_name=robot_name,# type: ignore
                phone=account.phone,# type: ignore
                postal_code=area_code,# type: ignore
                last_ip=ip_addr# type: ignore
            )
            
            emoji_dict = EmojiService.get_emoji_pack_dict_by_id(robot.cur_emoji_pack_id)
            timbre_dict = TimbreService.get_timbre_dict_by_id(robot.cur_timbre_id)
            funcs_dict = fun_domain.to_dict()
            character_dict = CharacterService.get_character_dict_by_id(robot.cur_charater_id)
            data= {'task_id':'',
                   'robot':robot.to_dict(),
                   'emoji':emoji_dict,
                   'timbre':timbre_dict,
                   'funcs':funcs_dict,
                   'character':character_dict}
            result = RobotRemoteService.active_notify(robot_id=robot_id,config=data)
            success,task_id = result
            if not success:
                db.session.rollback()
                raise RobotActiveNotifyError(task_id)
            data['task_id'] = task_id
            db.session.add(rob_extra_info)
            db.session.commit()
            return data
        # except RobotActiveNotifyError:
        #     db.session.rollback()
        #     raise RobotActiveNotifyError()
        # except EmojiPackageNotExistError as e:
        #     db.session.rollback()
        #     raise e
        # except TimbreNotExistError:
        #     db.session.rollback()
        #     raise TimbreNotExistError()
        # except CharacterNotExistError:
        #     db.session.rollback()
        #     raise CharacterNotExistError()
        except Exception as e:
            db.session.rollback()
            raise e
        
        
    @staticmethod
    def get_characters_by_robot(robot_id:str)->list[RobCharacter]|None:
        try:
            robot = db.session.get(Robots,robot_id)
            if robot:
                characters = db.session.query(RobCharacter).join(RobotCharacterMap,RobotCharacterMap.character_id==RobCharacter.id).filter(RobotCharacterMap.robot_id==robot_id).all()
                return characters
        except Exception as e:
            raise e
        return None
    
    @staticmethod
    def get_timbres_by_robot(robot_id)->list[RobTimbre]:
        try:
            robot = db.session.get(Robots,robot_id)
            if robot:
                timbres = []
                timbre_ids = []
                if robot.fun_domain:
                    timbres = robot.fun_domain.timbres
                    timbre_ids = [str(timbre.id) for timbre in timbres]
                if robot.extra_timbres:
                    for pack_id in robot.extra_timbres:
                        if pack_id in timbre_ids:
                            continue
                        timbre = db.session.get(RobTimbre,pack_id)
                        if timbre:
                            timbres.append(timbre)
                return timbres
        except Exception as e:
            logging.error(e)
        return []
    
    @staticmethod
    def get_emoji_packs_by_robot(robot_id)->list[RobEmojiPack]:
        try:
            robot = db.session.get(Robots,robot_id)
            if robot:
                emojipacks = []
                emojipack_ids = []
                if robot.fun_domain:
                    emojipacks = robot.fun_domain.emoji_packs
                    emojipack_ids = [str(emojipack.id) for emojipack in emojipacks]
                if robot.extra_emoji_packs:
                    for pack_id in robot.extra_emoji_packs:
                        if pack_id in emojipack_ids:
                            continue
                        emojipack = db.session.get(RobEmojiPack,pack_id)
                        if emojipack:
                            emojipacks.append(emojipack)
                return emojipacks
        except Exception as e:
            logging.error(e)
        return []
    

    @staticmethod
    def update_robot_config(account:AccountWrap|None,robot_id:str,args:dict)->RobotExtraInfo|None:
        try:
            if not account:
                raise HTTPNotLoginError()
            control_param = {}
            robot = db.session.get(Robots,robot_id)
            if not robot:
                raise RobotNotExistError(robot_id)
            if not robot.activated_at:
                raise RobotNotActiveError()
            
            if "character_id" in args and args['character_id'] and robot.cur_charater_id!=args["character_id"]:
                character = db.session.get(RobCharacter,args["character_id"])
                if character:
                    robot.cur_charater_id = character.id
                    control_param["character_id"] = args["character_id"]
                    control_param["character_personality"] = character.personality
                    control_param["character_agent_id"] = str(character.agent_id)
                else:
                    raise CharacterNotExistError(args.get("character_id","None"))
            if "timbre_id" in args and args["timbre_id"] and robot.cur_timbre_id!=args["timbre_id"]:
                timbre = db.session.get(RobTimbre,args["timbre_id"])
                if timbre:
                    if robot.chat_language and robot.chat_language not in timbre.suport_languages:
                        raise TimbreNotSupportLanguageError(timbre.name,robot.chat_language)    
                    
                    robot.cur_timbre_id = timbre.id
                    control_param["timbre_id"] = args["timbre_id"]
                    control_param["timbre_code"] = timbre.timbre_code
                    control_param["timbre_proivder"] = timbre.provider.provider_code if timbre.provider else None
                else:
                    raise TimbreNotExistError(args.get("timbre_id","None"))
            if "emoji_pack_id" in args and args['emoji_pack_id'] and robot.cur_emoji_pack_id!=args["emoji_pack_id"]:
                emoji_pack = db.session.get(RobEmojiPack,args["emoji_pack_id"])
                if emoji_pack:
                    robot.cur_emoji_pack_id = emoji_pack.id
                    control_param["emoji_pack_id"] = args["emoji_pack_id"]
                    control_param["emoji_pack_params"]=emoji_pack.to_dict()
                else:
                    raise EmojiPackageNotExistError(args.get("emoji_pack_id","None"))
            
            if robot.extra_info and "postal_code" in args and args['postal_code'] and robot.extra_info.postal_code!=args["postal_code"]:
                robot.extra_info.postal_code = args["postal_code"]
                # control_param["postal_code"] = args["postal_code"]
            if robot.extra_info and "user_name" in args and args['user_name'] and robot.extra_info.user_name!=args["user_name"]:
                robot.extra_info.user_name = args["user_name"]
            if robot.extra_info and "robot_name" in args and args['robot_name'] and robot.extra_info.robot_name!=args["robot_name"]:
                robot.extra_info.robot_name = args["robot_name"]
            if 'volume' in args and args['volume'] and args['volume']>0 and args['volume'] <=100:
                control_param["volume"] = args["volume"]
            if 'brightness' in args and args['brightness'] and args['brightness']>0 and args['brightness'] <=100:
                control_param["brightness"] = args["brightness"]
            if control_param:
                result = RobotRemoteService.remote_config(robot_id=robot_id,config_param=control_param)
                if result:
                    success,task_id = result
                    logging.info(f'Remote config success.success{success},{task_id}')
                    if not success:
                        message = task_id
                        raise RobotRemoteConfigError(message)
            robot.updated_at = datetime.now()
            robot.updated_by = account.id
            db.session.commit()
            return robot.extra_info
        except Exception as e:
            db.session.rollback()
            logging.error(e,stack_info=True)
            raise e

# parser.add_argument('id', type=str, required=False,location='args')
#         parser.add_argument('hardware_version',type=str,required=False,location='args')
#         parser.add_argument('fireware_version',type=str,required=False,location='args')
#         parser.add_argument('is_active',type=bool,required=False,default=None,location='args')
#         parser.add_argument('fun_domain_id',type=str,required=False,location='args')
#         parser.add_argument('page',type=int,required=False,deafult=-1,location='args')
#         parser.add_argument('page_size',type=int,required=False,deafult=-1,location='args')
    @staticmethod
    def get_robot_list(tenant_id,args:dict)->dict:
        query = db.session.query(Robots).filter(Robots.tenant_id==tenant_id)
        has_more = False
        total = 0
        try:
            if 'id' in args and args['id']:
                query = query.filter(Robots.id==args['id'])
                total = query.count()
            else:
                if 'hardware_version' in args and args['hardware_version']:
                    query = query.filter(Robots.h_version==args['hardware_version'])
                if 'fireware_version' in args and args['fireware_version']:
                    query = query.filter(Robots.f_version==args['fireware_version'])
                if 'is_active' in args and args['is_active'] is not None:
                    if args['is_active']:
                        query = query.filter(Robots.activated_at.isnot(None))
                    else:
                        query = query.filter(Robots.activated_at.is_(None))
                if 'fun_domain_id' in args and args['fun_domain_id']:
                    query = query.filter(Robots.fun_domain_id==args['fun_domain_id'])
                total = query.count()
                if 'page' in args and args['page']>0 and 'page_size' in args and args['page_size']>0:
                    query = query.offset((args['page']-1)*args['page_size']).limit(args['page_size'])
                    has_more = total > args['page_size'] * args['page']
            data = query.all()
            return {
            "total": total,
            "has_more": has_more,
            "data": data
            }
        except Exception as e:
            logging.error(e)
            raise e
        
        
    @staticmethod
    def bind_characters(robot_id,characters:list[RobCharacter]=[],submit:bool=True)->list[RobotCharacterMap]:
        robot_character_maps = []
        new_character_ids = [str(char.id) for char in characters]
        for character in characters:
            exist_map = db.session.query(RobotCharacterMap).filter(
                RobotCharacterMap.character_id == character.id,
                RobotCharacterMap.robot_id == robot_id
            )
            if exist_map:
                continue
            robot_character_map = RobotCharacterMap(
                robot_id=robot_id,# type:ignore
                character_id=character.id # type:ignore
            )
            db.session.add(robot_character_map)
            robot_character_maps.append(robot_character_map)
        db.session.query(RobotCharacterMap).filter(
            RobotCharacterMap.robot_id == robot_id,
            ~RobotCharacterMap.character_id.in_(new_character_ids)
        ).delete(synchronize_session='fetch')
        if submit:
            db.session.commit()
        return robot_character_maps
    
    @staticmethod
    def create_robot(account:AccountWrap,remote_ip:str,args:dict)->Robots:
        try:
            fun_domain_id = args.get("fun_domain_id",None)
            if not fun_domain_id:
                raise RobotParameterError(_("Function domain ID cannot be empty."))
            fun_domain = db.session.get(RobFunDomain,fun_domain_id)
            if not fun_domain:
                raise FunDomainNotExistError(fun_domain_id)
            
            robot_id = args.get("id",None)
            if not robot_id:
                raise ValueError(_("Robot id is required."))
            # h_ver = args.get("hardware_version",None)
            # f_ver = args.get("fireware_version",None)
            agent_type = args.get("agent_type",None)
            agent_type = AgentType(agent_type)
            extra_funcs =  args.get("extra_funcs",{})
            extra_timbres = args.get("extra_timbres",{})
            extra_emoji_packs = args.get("extra_emoji_packs",{})
            chat_language = args.get('chat_language','zh')
            # if not h_ver or not f_ver or not agent_type:
            #     raise RobotParameterError(_("Hardware version, fireware version are required."))
            if not agent_type:
                raise RobotParameterError(f"{_("Agent type only support for agent type is required.")}:{args.get('agent_type','')}")
            robot = Robots(
                id = robot_id, # type: ignore
                tenant_id=account.current_tenant_id,# type: ignore
                agent_type=agent_type.value,# type: ignore
                fun_domain_id = fun_domain_id,# type: ignore
                cur_charater_id = fun_domain.default_character_id,# type: ignore
                cur_timbre_id = fun_domain.default_timbre_id,# type: ignore
                cur_emoji_pack_id = fun_domain.default_emoji_pack_id,# type: ignore
                extra_funcs = extra_funcs,# type: ignore
                extra_timbres = extra_timbres,# type: ignore
                extra_emoji_packs = extra_emoji_packs,# type: ignore
                created_by = account.id,# type: ignore
                chat_language = chat_language,# type:ignore
            )
            db.session.add(robot)
            db.session.flush()
            rob_character_maps = RobotsService.bind_characters(
                robot.id,
                fun_domain.characters,
                submit=False
                )
            LogService.log(
                account.current_tenant_id,
                account.id, 
                LogAction.CREATE_ROBOT, 
                f"User {account.name} create robot {robot.id}",
                remote_ip)
            db.session.commit()
            return robot
        except Exception as e:
            db.session.rollback()
            logging.error(e,stack_info=True)
            raise e
        
    @staticmethod
    def update_robot(account:AccountWrap,remote_ip:str,args:dict)->Robots:
        try:
            robot_id = args.get("id",None)
            if not robot_id:
                raise RobotParameterError(_("Robot id is required."))
            robot = db.session.get(Robots,robot_id)
            if not robot:
                raise RobotNotExistError(robot_id)
            
            fun_domain_id = args.get("fun_domain_id",None)
            if not fun_domain_id:
                raise RobotParameterError(_("Function domain ID cannot be empty."))
            # h_ver = args.get("hardware_version",None)
            # f_ver = args.get("fireware_version",None)
            agent_type = args.get("agent_type",None)
            agent_type = AgentType(agent_type)
            extra_funcs =  args.get("extra_funcs",{})
            extra_timbres = args.get("extra_timbres",{})
            extra_emoji_packs = args.get("extra_emoji_packs",{})
            chat_language = args.get('chat_language','zh')
            # if not h_ver or not f_ver or not agent_type:
            #     raise RobotParameterError(_("Hardware version, fireware version are required."))
            if not agent_type:
                raise RobotParameterError(f"{_("Agent type only support for agent type is required.")}:{args.get('agent_type','')}")
            robot.agent_type = agent_type.value
            robot.extra_funcs = extra_funcs
            robot.extra_timbres = extra_timbres
            robot.extra_emoji_packs = extra_emoji_packs
            robot.chat_language = chat_language
            if robot.fun_domain_id != fun_domain_id:
                fun_domain = db.session.get(RobFunDomain,fun_domain_id)
                if not fun_domain:
                    raise FunDomainNotExistError(fun_domain_id)
            
                rob_character_maps = RobotsService.bind_characters(
                    robot.id,
                    fun_domain.characters,
                    submit=False
                    )
            db.session.flush()
            LogService.log(
                account.current_tenant_id,
                account.id, 
                LogAction.CREATE_ROBOT, 
                f"User {account.name} create robot {robot.id}",
                remote_ip)
            db.session.commit()
            return robot
        except Exception as e:
            db.session.rollback()
            logging.error(e,stack_info=True)
            raise e
        
    @staticmethod
    def delete_robot(current_user:AccountWrap,robot_id:str,remote_ip:str):
        try:
            robot = db.session.get(Robots,robot_id)
            if not robot:
                raise RobotNotExistError(robot_id)
            db.session.delete(robot)
            LogService.log(current_user.current_tenant_id,current_user.id,LogAction.DEL_ROBOT,f"User {current_user.name} delete robot {robot.id}",remote_ip,submit=False)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            logging.error(e,stack_info=True)
            raise BaseHTTPException(description=f"{_("Delete robot error.")}:{e}")
        
    @staticmethod
    def import_robots(account:AccountWrap, df:DataFrame,agent_type:AgentType|None,fun_domain_id:str|None, character_id:str|None, timbre_id:str|None, emoji_pack_id:str|None, extra_funcs:dict, extra_timbres:dict, extra_emoji_packs:dict,chat_language:str|None, ip_addr:str)->tuple[list[Robots],list[str]]:
        robot_list = []
        messages = []
        tenant_id = account.current_tenant_id
        fun_domain_map = {}
        now = datetime.now()
        if character_id:
            character = db.session.get(RobCharacter, character_id)
            if not character:
                raise CharacterNotExistError(character_id)
        if timbre_id:
            timbre = db.session.get(RobTimbre, timbre_id)
            if not timbre:
                raise TimbreNotExistError(timbre_id)
        if emoji_pack_id:
            emoji_pack = db.session.get(RobEmojiPack, emoji_pack_id)
            if not emoji_pack:
                raise EmojiPackageNotExistError(emoji_pack_id)
        try:
            for _,row in df.iterrows():
                robot_id = row["id"]
                robot = db.session.get(Robots,robot_id)
                if robot is not None:
                    continue
                _agent_type = AgentType(row["agent_type"]) if row.get("agent_type") else None
                _agent_type = agent_type if agent_type else _agent_type
                if not _agent_type:
                    messages.append(f"机器人{robot_id}导入失败,未知的类型:{row['agent_type']}:{agent_type.value if agent_type else ''}")
                    continue
                _fun_domain_id = row.get("fun_domain_id")
                _fun_domain_id = fun_domain_id if fun_domain_id else _fun_domain_id
                if not _fun_domain_id:
                    messages.append(f"机器人{robot_id}导入失败,未知的套餐:{row['fun_domain_id']}")
                    continue

                _chat_language = row.get("chat_language")
                _chat_language = _chat_language if _chat_language else chat_language
                if not _chat_language:
                    _chat_language = "zh"
                domain_config = fun_domain_map.get(_fun_domain_id)
                if not domain_config:
                    domain = db.session.get(RobFunDomain, _fun_domain_id)
                    if not domain:
                        messages.append(f"机器人{robot_id}导入失败,套餐{_fun_domain_id}不存在")
                        continue
                    else:
                        fun_domain_map[_fun_domain_id] = [domain.default_character_id,domain.default_timbre_id,domain.default_emoji_pack_id]
                robot = Robots(
                    id = robot_id,# type:ignore
                    tenant_id = tenant_id,# type:ignore
                    agent_type = _agent_type.value,# type:ignore
                    fun_domain_id = _fun_domain_id,# type:ignore
                    cur_charater_id = character_id if character_id else fun_domain_map[_fun_domain_id][0],# type:ignore
                    cur_timbre_id = timbre_id if timbre_id else fun_domain_map[_fun_domain_id][1],# type:ignore
                    cur_emoji_pack_id = emoji_pack_id if emoji_pack_id else fun_domain_map[_fun_domain_id][2],# type:ignore
                    chat_language = _chat_language,# type:ignore
                    extra_funcs = extra_funcs,# type:ignore
                    extra_timbres = extra_timbres,# type:ignore
                    extra_emoji_packs = extra_emoji_packs,# type:ignore
                    created_at = now,# type:ignore
                    created_by = account.id,# type:ignore
                )    
                db.session.add(robot)
                db.session.flush()
                RobotsService.bind_characters(
                    robot.id,
                    domain.characters ,# type:ignore
                    submit=False,
                )
                robot_list.append(robot)
                LogService.log(account.current_tenant_id, account.id, LogAction.CREATE_ROBOT, f"User {account.name} import robot {robot_id}", ip_addr,submit=False)
            db.session.commit()
            return robot_list,messages
        except Exception as e:
            logging.error(e,stack_info=True)
        return [],messages
    
    @staticmethod
    def current_config(robot_id:str)->dict:
        try:
            robot = db.session.get(Robots,robot_id)
            if not robot:
                raise RobotNotExistError(robot_id)
            if not robot.extra_info:
                raise RobotNotActiveError(robot_id)
            cur_character = db.session.get(RobCharacter,robot.cur_charater_id)
            if not cur_character:
                raise CharacterNotExistError(robot.cur_charater_id)
            cur_emoji_pack = db.session.get(RobEmojiPack,robot.cur_emoji_pack_id)
            if not cur_emoji_pack:
                raise EmojiPackageNotExistError(robot.cur_emoji_pack_id)
            cur_timbre = db.session.get(RobTimbre,robot.cur_timbre_id)
            if not cur_timbre:
                raise TimbreNotExistError(robot.cur_timbre_id)
            result = {
                "robot":{
                    "agent_type":robot.agent_type,
                    "chat_language":robot.chat_language,
                    "user_name":robot.extra_info.user_name,
                    "postal_code":robot.extra_info.postal_code,
                    "robot_name":robot.extra_info.robot_name,
                }}
            character_dict = {
                "character_id":str(cur_character.id),
                "name":cur_character.name,
                "personality":cur_character.personality,
                "wakeup_sentences":cur_character.wakeup_sentences,
                "greet_sentence":cur_character.greet_sentence,
                "busy_sentences":cur_character.busy_sentences,
                "stepback_sentences":cur_character.stepback_sentences,
                "appearance_url":cur_character.appearance_url,
                "appearance_file_url":cur_character.appearance_file_url,
            }
            emoji_pack_dict = cur_emoji_pack.to_dict()
            timbre_dict = cur_timbre.to_dict()
            result["emji_packs"] = emoji_pack_dict
            result["timbre"] = timbre_dict
            result["character"] = character_dict
            return result
        except Exception as e:
            raise e

    @staticmethod
    def bind_status(robot_id:str, account_id:str)->dict:
        # 查询激活状态
        robot = db.session.get(Robots,robot_id)
        if not robot:
            raise RobotNotExistError(robot_id)
        if not robot.activated_at and not robot.extra_info:
            is_active = False
        else:
            is_active = True
        rob_extra_infos = db.session.query(RobotExtraInfo).filter(RobotExtraInfo.account_id==account_id,RobotExtraInfo.id==robot_id).first()
        if not rob_extra_infos:
            is_self = False
        else:
            is_self = True
        # 查询绑定状态
        # 返回结果
        return {
            "is_active":is_active,
            "is_self":is_self,
        }
